/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dp1.pucp.Simulacion.DAO;
import com.dp1.pucp.Modelo.Clases.*;
import com.dp1.pucp.Util.HibernateUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Rodrigo
 */
public class SimulacionDAO {
   
        public void guardarSimulacion(Simulacion simulacion) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            session.saveOrUpdate(simulacion);
            tx.commit();
        } catch (HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
        }
    }
      public void guardarDemandaxpedidoproducto(Demandaxpedidoproducto dempedido) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            session.saveOrUpdate(dempedido);
            tx.commit();
        } catch (HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
        }
    }
        
        public Simulacion guardarSimulacion2(Simulacion simulacion){
         Simulacion c = new Simulacion();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx =  session.beginTransaction();
        try {
            session.saveOrUpdate(simulacion);
            session.flush();
         
        }catch(HibernateException e) {
            //System.out.println(e.getMessage());
            e.printStackTrace();
            throw new HibernateException(e);
            
        } finally {
            
            session.persist(simulacion);
            
            int cod = simulacion.getIdsimulacion();
            
            List lista = session.createQuery("from Simulacion where idsimulacion="+cod).list();        
            Iterator iter = lista.iterator();
            while (iter.hasNext()) { 
                c = (Simulacion) iter.next();
            }        
            tx.commit();
            session.close();
            return c;
        }
        
    }
        
    public void guardarEmpxmaqsimu(Empleadoxmaquinasimulacion emp){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            session.saveOrUpdate(emp);
            tx.commit();
        } catch (HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
        }
        
     }
    public void guardarProdSim(Productosimulacion prodsim){
         Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            session.saveOrUpdate(prodsim);
            tx.commit();
        } catch (HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
        }
        
    
    }
    public ArrayList<Maquina> listarMaquinas2(){
        
        ArrayList<Maquina> arreglo = new ArrayList<Maquina>();
        
        Maquina maq1 = new Maquina();
        Tipomaquina tipo = new Tipomaquina();
        tipo.setIdtipomaquina(1);
        tipo.setNombre("Horneado");
        maq1.setIdmaquina(1);
        maq1.setCodigo("MAC1");
        maq1.setEstado(1);
        maq1.setMaxProduccion(500);
        maq1.setTipomaquina(tipo);
        Date fecha = new Date();
        maq1.setFechaIngreso(fecha);
        maq1.setEstado(0);
        
        arreglo.add(maq1);
        
        return arreglo;
        
    }
    
    
    public void guardarParametros(Parametrosalgoritmo parametros){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            session.saveOrUpdate(parametros);
            tx.commit();
        } catch (HibernateException e) {
            throw new HibernateException(e);
        } finally {
            session.close();
        }
        
    }
    
    
    public ArrayList<Historico> historiaEmpleado(int id, int turno){
        ArrayList<Historico> historias = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
//            String cad = ;
//            Query query = session.createQuery("from historico  where idempleado = :idemp");
//            query.setParameter("idemp", id);
           // List lista = session.createQuery("from RecetaPfMp where idreceta_pf_mp="+u.getIdrecetaPfMp()+"").list(); 
           //List lista = session.createQuery("from Pedidoproducto where idpedidoproducto="+cod).list();  
            List lista = session.createQuery("from Historico where idempleado="+id+" and turno="+turno+" order by idhistorico").list();       
            Iterator iter = lista.iterator();
            while (iter.hasNext()) {    
                Historico h = (Historico) iter.next();
                Hibernate.initialize(h.getIdhistorico());          
                Hibernate.initialize(h.getEmpleado());             
                Hibernate.initialize(h.getTipomaquina());
                Hibernate.initialize(h.getProduccion());
                Hibernate.initialize(h.getMerma());
                Hibernate.initialize(h.getFecha());
                Hibernate.initialize(h.getTurno());

                historias.add(h);
            }        
            tx.commit();
        } catch(HibernateException e) {
            e.printStackTrace();
            throw new HibernateException(e);    
        } finally {
            session.close();
            return historias;
        }
    }
    
    public Tipoproducto getTipoProductoId(int id){
        
        Tipoproducto tipo = new Tipoproducto();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            String cad = "from Tipoproducto T where T.idtipoproducto = :idtipo";
            Query query = session.createQuery(cad);
            query.setParameter("idtipo", id);
            List lista = query.list();       
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {   
                tipo = (Tipoproducto) iter.next();
                Hibernate.initialize(tipo.getIdtipoproducto());          
                Hibernate.initialize(tipo.getDescripcion());             
                Hibernate.initialize(tipo.getNombre());
                Hibernate.initialize(tipo.getEstado());
                Hibernate.initialize(tipo.getFactorVol());
                Hibernate.initialize(tipo.getMaxPolitica());
                Hibernate.initialize(tipo.getMinPolitica());
                Hibernate.initialize(tipo.getTipo());
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return tipo;  
    }
    
    public Tipoproducto getTipoProductoNombre(String nombre){
        
        Tipoproducto tipo = new Tipoproducto();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            String cad = "from Tipoproducto T where T.nombre = :nombretipo";
            Query query = session.createQuery(cad);
            query.setParameter("nombretipo", nombre);
            List lista = query.list();       
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {   
                tipo = (Tipoproducto) iter.next();
                Hibernate.initialize(tipo.getIdtipoproducto());          
                Hibernate.initialize(tipo.getDescripcion());             
                Hibernate.initialize(tipo.getNombre());
                Hibernate.initialize(tipo.getEstado());
                Hibernate.initialize(tipo.getFactorVol());
                Hibernate.initialize(tipo.getMaxPolitica());
                Hibernate.initialize(tipo.getMinPolitica());
                Hibernate.initialize(tipo.getTipo());
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return tipo;  
    } 
    
    public ArrayList<Maquina> listarMaquinas(){
        ArrayList<Maquina> maquinas = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            List lista = session.createQuery("from Maquina order by idmaquina").list();        
            Iterator iter = lista.iterator();
            while (iter.hasNext()) {    
                Maquina m = (Maquina) iter.next();
                Hibernate.initialize(m.getIdmaquina());
                Hibernate.initialize(m.getCodigo());
                Hibernate.initialize(m.getTipomaquina());
                Hibernate.initialize(m.getMaxProduccion());
                Hibernate.initialize(m.getFechaIngreso());
                Hibernate.initialize(m.getTrabajos());
                Hibernate.initialize(m.getFechaIngreso());
                Hibernate.initialize(m.getEstado());
                maquinas.add(m);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();
            return maquinas;
        }
        
    }
    
    public ArrayList<String> listarEstado()     {
        ArrayList<String> turnos = new ArrayList<>();
        turnos.add("Turno 1");
        turnos.add("Turno 2");
        turnos.add("Turno 3");
        return turnos;
    }
    
    public ArrayList<Empleado> listarOperarios(){
        //falta implementar
      ArrayList<Empleado> empleados = new ArrayList();
        return empleados;
    }
    
    
    public ArrayList<RecetaPfPi> getIdTipoProductoIntermedio(int id){
        
        ArrayList<RecetaPfPi> recetas = new ArrayList<RecetaPfPi>();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            List lista = session.createQuery("from RecetaPfPi  where idtipoproducto_pf ="+id+" order by idtipoproducto_pi asc").list();
                 
            Iterator iter = lista.iterator();
            while (iter.hasNext()) {   
                RecetaPfPi receta = (RecetaPfPi) iter.next();
                Hibernate.initialize(receta.getIdrecetaPfPi());          
                Hibernate.initialize(receta.getCantidad());             
                Hibernate.initialize(receta.getTipoproductoByIdtipoproductoPf());
                Hibernate.initialize(receta.getTipoproductoByIdtipoproductoPi());
                recetas.add(receta);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return recetas;  
        
    }
    
    
    public Productoxmaquina getProductoxMaquina(int id){//, int tipomaquina){
        
        Productoxmaquina prodmaq = new Productoxmaquina();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            String cad = "from Productoxmaquina R where R.idtipoproducto = :idtipo";// and R.tipomaquina = :tipomaquin";
            Query query = session.createQuery(cad);
            query.setParameter("idtipo", id);
            //query.setParameter("tipomaquin", tipomaquina);
            List lista = query.list();       
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {   
                prodmaq = (Productoxmaquina) iter.next();
                Hibernate.initialize(prodmaq.getIdproductoxmaquina());          
                Hibernate.initialize(prodmaq.getPorcentajeCosto());             
                Hibernate.initialize(prodmaq.getPorcentajePrecio());
                Hibernate.initialize(prodmaq.getMerma());
                Hibernate.initialize(prodmaq.getTiempo());
                Hibernate.initialize(prodmaq.getTipomaquina());
                Hibernate.initialize(prodmaq.getTipoproducto());
                Hibernate.initialize(prodmaq.getTipomerma());
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return prodmaq;  
        
        
    }
    
    public Parametrosalgoritmo getParametros(){
        
        ArrayList<Parametrosalgoritmo> parametros = new ArrayList<Parametrosalgoritmo>();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            List lista = session.createQuery("from Parametrosalgoritmo order by idparametrosalgoritmo").list();     
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {   
                Parametrosalgoritmo param = (Parametrosalgoritmo) iter.next();
                Hibernate.initialize(param.getIdparametrosalgoritmo());          
                Hibernate.initialize(param.getIteracionesgrasp());             
                Hibernate.initialize(param.getFGrasp());
                Hibernate.initialize(param.getTemperaturaFinal());
                Hibernate.initialize(param.getTemperaturaInicial());
                Hibernate.initialize(param.getFactorEnfriamiento());
                parametros.add(param);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }
        if (parametros.size()==0){
            Parametrosalgoritmo papa = new Parametrosalgoritmo();
            papa.setIdparametrosalgoritmo(0);
            return papa;
        }else{
            return parametros.get(parametros.size()-1);
        }
//        System.out.println("ERROR: "+parametros.size());
//        return parametros.get(parametros.size()-1);       
    }
    
    public Empleado buscarEmpleadoConArreglo(int id, ArrayList<Empleado> arreglo){
        
        for (int i=0; i<arreglo.size(); i++){
            if (arreglo.get(i).getIdempleado()==id){
                return arreglo.get(i);
            }
        }
        
        return null;
    }
    
    public ArrayList<Productoxmaquina> procesoxProd(int idtipo){//falta añadir lo nuvos campos
     ArrayList<Productoxmaquina> procesos = new ArrayList();
     Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
         List lista = session.createQuery("from Productoxmaquina where idtipoproducto="+ idtipo +"").list();
         Iterator iter = lista.iterator();
           while (iter.hasNext()) {    
                Productoxmaquina p = (Productoxmaquina) iter.next();
                Hibernate.initialize(p.getIdproductoxmaquina());
                Hibernate.initialize(p.getPorcentajePrecio());
                Hibernate.initialize(p.getPorcentajePrecio());
                Hibernate.initialize(p.getMerma());
                Hibernate.initialize(p.getTiempo());
                Hibernate.initialize(p.getTipomaquina());
                Hibernate.initialize(p.getTipoproducto());             
              //  Hibernate.initialize(p.getTipomerma());  MIRAAAAAAAAAAAAAAAAA
                procesos.add(p);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();
            return procesos;
        }   
        }
    
    public float getPrecio(int idgal){
        
        Precio prec = new Precio();
         Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
          try{
            List lista = session.createQuery("from Precio where idtipoproducto="+idgal+"").list();     
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {   
                 prec = (Precio)iter.next();
                Hibernate.initialize(prec.getIdprecio());          
                Hibernate.initialize(prec.getPrecio());             
//                Hibernate.initialize(prec.getMoneda());
//                Hibernate.initialize(prec.getFechainicio());
//                Hibernate.initialize(prec.getFechafin());
//                Hibernate.initialize(prec.getTipoproducto());
                
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return prec.getPrecio() ;  
    }
    
  
    public ArrayList<Productointermedio> getInvInicial(int idtipo){//falta
       ArrayList<Productointermedio> listapi = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
            List lista = session.createQuery("from Productointermedio where idtipoproducto1="+idtipo+" order by idtipoproducto2 asc").list();     
            Iterator iter = lista.iterator();
          while (iter.hasNext()) {
                Productointermedio prodint = (Productointermedio)iter.next();
                Hibernate.initialize(prodint.getIdproductointermedio());          
                Hibernate.initialize(prodint.getTipoproductoByIdtipoproducto1());    
                Hibernate.initialize(prodint.getTipoproductoByIdtipoproducto2());                              
                Hibernate.initialize(prodint.getAlmacen());
                Hibernate.initialize(prodint.getCodigo());
                Hibernate.initialize(prodint.getDescripcion());
                Hibernate.initialize(prodint.getEstado());
                Hibernate.initialize(prodint.getVolumen());
                Hibernate.initialize(prodint.getFechaCaducidad());
                Hibernate.initialize(prodint.getLote());
                //añadir el campo tipoproducto2
                listapi.add(prodint);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return listapi;
    }
    
    public Productointermedio getprodInt(int idtipo){//falta
      Productointermedio prod = new Productointermedio();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
            List lista = session.createQuery("from Productointermedio where idtipoproducto2="+idtipo+"").list();     
            Iterator iter = lista.iterator();
          if (iter.hasNext()) {
                 prod = (Productointermedio)iter.next();
                Hibernate.initialize(prod.getIdproductointermedio());          
                Hibernate.initialize(prod.getTipoproductoByIdtipoproducto1());    
                Hibernate.initialize(prod.getTipoproductoByIdtipoproducto2());                              
                Hibernate.initialize(prod.getAlmacen());
                Hibernate.initialize(prod.getCodigo());
                Hibernate.initialize(prod.getDescripcion());
                Hibernate.initialize(prod.getEstado());
                Hibernate.initialize(prod.getVolumen());
                Hibernate.initialize(prod.getFechaCaducidad());
                Hibernate.initialize(prod.getLote());
                
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return prod;
    }

    
    
    public ArrayList<Pedidoproducto> getPedidosProductoxEstado(int estado){//falta
       ArrayList<Pedidoproducto> listapi = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
            List lista = session.createQuery("from Pedidoproducto where Estado="+estado+" and motivo="+"'Por Politica'"+" order by idpedidoproducto asc").list();     
            Iterator iter = lista.iterator();
          while (iter.hasNext()) {
                Pedidoproducto pedido = (Pedidoproducto)iter.next();
                Hibernate.initialize(pedido.getIdpedidoproducto());          
                Hibernate.initialize(pedido.getCliente());    
                Hibernate.initialize(pedido.getEstado());                              
                Hibernate.initialize(pedido.getFechaEntrega());
                Hibernate.initialize(pedido.getFechaRegistro());
                Hibernate.initialize(pedido.getIgv());
                Hibernate.initialize(pedido.getTotal());
                listapi.add(pedido);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return listapi;
    
    
    }
    
    public ArrayList<Demandaxpedidoproducto> getPedidosProductoxdemanda(int demanda){//falta
       ArrayList<Demandaxpedidoproducto> listapi = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
            List lista = session.createQuery("from Demandaxpedidoproducto where iddemanda="+demanda+" order by idpedidoproducto asc").list();     
            Iterator iter = lista.iterator();
          while (iter.hasNext()) {
                Demandaxpedidoproducto pedido = (Demandaxpedidoproducto)iter.next();
                Hibernate.initialize(pedido.getIddemandaxpedidoproducto());          
                Hibernate.initialize(pedido.getDemanda());          
                Hibernate.initialize(pedido.getPedidoproducto());
                   
                Hibernate.initialize(pedido.getPedidoproducto().getIdpedidoproducto());  
                
                listapi.add(pedido);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return listapi;
    
    
    }
    
    public ArrayList<Productosimulacion> getProductosSimulacion(Simulacion simulacion){
        
        ArrayList<Productosimulacion> listapi = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try{
            List lista = session.createQuery("from Productosimulacion where idsimulacion="+simulacion.getIdsimulacion()+" order by idproductosimulacion desc").list();     
            Iterator iter = lista.iterator();
          while (iter.hasNext()) {
                Productosimulacion p = (Productosimulacion)iter.next();
                Hibernate.initialize(p.getIdproductosimulacion());          
                Hibernate.initialize(p.getTipoproducto());    
                Hibernate.initialize(p.getSimulacion());                              
                Hibernate.initialize(p.getProdReal());
                Hibernate.initialize(p.getMermaReal());
                Hibernate.initialize(p.getCantProducida());
                Hibernate.initialize(p.getCantMerma());
                listapi.add(p);
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return listapi;
        
    }
    
    
    public Cliente getClienteId(int id){
        
        Cliente c = new Cliente();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            String cad = "from Cliente where idcliente = :idtipo";
            Query query = session.createQuery(cad);
            query.setParameter("idtipo", id);
            List lista = query.list();       
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {   
                c = (Cliente) iter.next();
                Hibernate.initialize(c.getIdcliente());          
                Hibernate.initialize(c.getCodigo());             
                Hibernate.initialize(c.getDireccionfiscal());
                Hibernate.initialize(c.getDistrito());
                Hibernate.initialize(c.getRazonsocial());
                Hibernate.initialize(c.getTelefono());
                Hibernate.initialize(c.getTelefono());
                Hibernate.initialize(c.getTipocliente());
                Hibernate.initialize(c.getEstado());
                Hibernate.initialize(c.getPaginaweb());
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return c;  
    }
    
    public Superhombre getSuperHombre(int idempleado){
        
        Superhombre s = new Superhombre();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            String cad = "from Superhombre where idempleado = :id";
            Query query = session.createQuery(cad);
            query.setParameter("id", idempleado);
            List lista = query.list();       
            Iterator iter = lista.iterator();
            if (iter.hasNext()) {   
                s = (Superhombre) iter.next();
                Hibernate.initialize(s.getIdsuperhombre());      
                Hibernate.initialize(s.getEmpleado());
                Hibernate.initialize(s.getEstado());
                Hibernate.initialize(s.getProduccionEmpaquetado());
                Hibernate.initialize(s.getProduccionHorneado());
                Hibernate.initialize(s.getProduccionRellenado());
                Hibernate.initialize(s.getProduccionDecorado());
                Hibernate.initialize(s.getMermaHorneado());
                Hibernate.initialize(s.getMermaDecorado());
                Hibernate.initialize(s.getMermaRellenado());
                Hibernate.initialize(s.getMermaEmpaquetado());
            }        
            tx.commit();
        } catch(HibernateException e) {
            throw new HibernateException(e);    
        } finally {
            session.close();           
        }              
        return s; 
        
    }
    
    

}

   